//
//  OrderInfoViewController.swift
//  DiDiRecycle
//
//  Created by abb on 16/8/8.
//  Copyright © 2016年 abb. All rights reserved.
//

import UIKit
import SVProgressHUD
let OrdersInfoCellReuseIdentifier = "OrdersInfoCellReuseIdentifier"
class OrderInfoViewController: AbbBaseViewController {
    /// 订单模型
    var order:Order? {
        didSet {
            if order != nil{
                valueArr.append("\(order!.id)")
                valueArr.append(order!.name!)
                valueArr.append(order!.contactName!)
                valueArr.append(order!.contactPhoneNumber!)
                valueArr.append(order!.address! + order!.addressDetailed!)
                valueArr.append(NSDate.StrFromTimeStamp(timestamp: order!.arrangeTime))
                tableView.reloadData()
            }
        }
    }
    var user:User?
    /// 详情key数组
    var keyArr:[String] = [
        "订单号",
        "类型",
        "联系人",
        "联系电话",
        "联系地址",
        "预约时间"
    ]
    /// 详情value数组
    var valueArr:[String] = []
    
    
    func orderReceiving() {
        SVProgressHUD.showWithStatus("请稍等")
        OrderDAO.orderReceiving(order!.orderID, DGYunTuId: order!.id) { (success, result) in
            if success {
                SVProgressHUD.showSuccessWithStatus(result)
                let vc = self.navigationController?.viewControllers[self.navigationController!.viewControllers.count - 2] as! HomeViewController
                vc.refreshOrder = true
                self.navigationController?.popToViewController(vc, animated: true)
            } else {
                SVProgressHUD.showErrorWithStatus(result)
            }
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        SVProgressHUD.setMinimumDismissTimeInterval(1)
        SVProgressHUD.setDefaultMaskType(.Clear)
        
    }

    private func setupUI() {
        // 添加子控件
        view.addSubview(tableView)
        view.addSubview(orderReceivingBtn)
        // 布局子控件
        orderReceivingBtn.snp_makeConstraints { (make) in
            make.left.right.bottom.equalTo(self.view)
            make.height.equalTo(self.view).multipliedBy(0.1)
        }
        tableView.snp_makeConstraints { (make) in
            make.top.right.left.equalTo(self.view)
            make.bottom.equalTo(orderReceivingBtn.snp_top)
        }
        
    }
    // MARK: - 懒加载
    private lazy var tableView:UITableView =  {
        let tbv = UITableView(frame: CGRectZero, style: .Plain)
        // 设置代理数据源
        tbv.delegate = self
        tbv.dataSource = self
        // 注册cell
        tbv.registerClass(OrdersInfoTableViewCell.self, forCellReuseIdentifier: OrdersInfoCellReuseIdentifier)
        // 隐藏多余cell
        tbv.tableFooterView = UIView()
        tbv.separatorStyle = UITableViewCellSeparatorStyle.None
        return tbv
    }()
    private lazy var orderReceivingBtn:UIButton = {
        let btn = UIButton()
        btn.backgroundColor = UIColor.tintColor()
        btn.setTitle("接单", forState: .Normal)
        btn.titleLabel?.textAlignment = NSTextAlignment.Center
        btn.addTarget(self, action: #selector(orderReceiving), forControlEvents: .TouchUpInside)
        return btn
    }()
    
}

extension OrderInfoViewController:UITableViewDelegate,UITableViewDataSource {
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 2
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        // 商户cell
        if section == 0 {
            return 1
        }
        // 详情cell
        return keyArr.count
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        // 商户cell
        if indexPath.section == 0 {
            let customCell:CustomTableViewCell = tableView.dequeueStaticCell(indexPath)
            customCell.delegate = self
            customCell.user = user
            return customCell
        }

        // 订单详情cell'
        let cell = tableView.dequeueReusableCellWithIdentifier(OrdersInfoCellReuseIdentifier, forIndexPath: indexPath) as! OrdersInfoTableViewCell
        cell.key = keyArr[indexPath.row]
        cell.value = valueArr[indexPath.row]
        print(valueArr[indexPath.row])
        return cell
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        // 商户cell
        if indexPath.section == 0 {
           return 150
        }
        // 订单详情cell
        let cell = tableView.dequeueReusableCellWithIdentifier(OrdersInfoCellReuseIdentifier) as! OrdersInfoTableViewCell
        
        let height = cell.rowHeight(valueArr[indexPath.row]) + 10
        print(height)
        return height
    }
    
    func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        // 商户cell
        if section == 0 {
            return nil
        }
        // 详情cell
        let hearView = HeadView(title: "详细信息", color: UIColor.darkGrayColor())
        return hearView
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 0
        }
        return 40
    }
    
}

extension OrderInfoViewController: CustomTableViewCellDelegate {
    func CilckDial() {
        if order?.contactPhoneNumber != nil && order?.contactPhoneNumber != "" {
            let alertController = UIAlertController(title: "拨打", message: order!.contactPhoneNumber, preferredStyle: UIAlertControllerStyle.Alert)
            let actionDone = UIAlertAction(title: "好", style: .Default, handler: { (action) in
                let phoneStr = String(format: "tel:%@",self.order!.contactPhoneNumber!)//"tel:\(self.order!.contactPhoneNumber!)"
                dispatch_after(UInt64(0.2), dispatch_get_main_queue(), {
                    UIApplication.sharedApplication().openURL(NSURL(string: phoneStr)!)
                })
            })
            let actionCancel = UIAlertAction(title: "取消", style: .Cancel, handler: nil)
            alertController.addAction(actionDone)
            alertController.addAction(actionCancel)
            self.presentViewController(alertController, animated: true, completion: nil)
        }
    }
}
